<?php
namespace app\driver\controller;

use app\admin\model\Bottle;
use app\admin\model\BottleExetLog;
use app\admin\model\BottleLog;
use app\common\Logic\BottleLogic;
use app\api\cache\TokenCache;
use app\api\controller\FeiHong;
use app\api\logic\LoginLogic;
use app\api\model\Order;
use app\api\model\OrderGoods;
use app\api\model\User;
use app\common\server\ConfigServer;
use app\common\server\WeChatServer;
use think\Db;
use think\Exception;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Request;
use app\driver\model\Driver as dri;

class Driver extends DriBase
{

    public $like_not_need_login = ['login', 'sms', 'turnInfo','bottleInput','siteList'];

    //登录
    public function login()
    {
        DB::startTrans();
        try{
            $data = Request::post();

            $result = $this->validate($data,'app\driver\validate\Driver.login');
            if($result !== true){
                throw new Exception($result);
            }
            $mobile = $data['mobile']; //手机号
            $verifyCode = $data['verify_code']; //验证码
            $code = $data['code']; //微信code  用来获取微信userID

            //判断手机验证码是否一致
            if ($verifyCode == 999999) {
                $smsCode = 999999; //测试专用
            } else {
                $smsCode = Cache::get('sms_'.$mobile);
            }
            if ($verifyCode != $smsCode) {
                throw new Exception('手机验证码错误');
            }
            $expire_time = time() + Config::get('project.token_expire_time');
            $token = md5("Driver_".$mobile.$expire_time);
            //判断用户存不存在
            $user = dri::where(['dmobile' => $mobile])->find();

            if (!$user) {
                //不存在直接注册为新用户登录后提示未绑定用户
                throw new Exception('用户不存在');
//                $post = request()->post();
//                $post['mobile'] = $mobile;
//                $token = LoginLogic::registerDriver($post);
//                $user = dri::where(['dmobile' => $mobile])->find();
            } else {
                //已经存在用户
                if ($user->dstatus == 2) {
                    throw new Exception('用户已被禁用');
                }
            }
            $row = Db::name('session')->where(['user_id' => $user->id, 'type' => 1])->find();
            $result = ['user_id' => $user->id, 'token' => $token, 'update_time' => time(), 'expire_time' =>$expire_time, 'type' => 1, 'client' => 1];
            if (!$row) {
                Db::name('session')->insert($result);
            } else {
                $row = $result;
                unset($row['user_id']);
                Db::name('session')->where(['user_id' => $user->id, 'type' => 1])->update($row);
            }

            $auth = Db::name('user_auth')->where(['user_id' => $user->id, 'type' => 1])->find();
            //获取用户的openId
            $getOpenArr = $this->getOpenId($code);


            $openid = $getOpenArr['openid'] ?? '';

            if (!$auth) {
                $dataArr['user_id'] = $user->id;
                $dataArr['openid'] = $openid;
                $dataArr['create_time'] = time();
                $dataArr['update_time'] = time();
                $dataArr['client'] = 1;  //微信小程序
                $dataArr['type'] = 1;
                Db::name('user_auth')->insert($dataArr);
            } else {
                if ($openid) {
                    Db::name('user_auth')->where(['user_id' => $user->id, 'type' => 1])->update(['update_time' => time(), 'openid' =>$openid]);
                }
            }


            $result['dtype'] = $user->dtype;
            Cache::rm('sms_'.$mobile);
            //该用户存在绑定小程序ID 待定
            Db::commit();
            $this->_success('登录成功', $result);
        }catch (Exception $e){
            DB::rollback();
            $this->_error($e->getMessage());
        }
    }

    //获取微信openid
    public function getOpenId($code)
    {
        $code = $code ?: $this->request->post('code');
        $config = WeChatServer::getOaConfig(); // 微信配置
        $appid = 'wx1db95109f11597f5';
        $secret = '093304e3ba2a035160705aa9c76ac4dc';

        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $secret . '&js_code=' . $code . '&grant_type=authorization_code';

        return (new FeiHong())->curl($url);
//        $data['openid'] = $obj["openid"];


    }

    //订单列表
    public function orderList()
    {
        $status = $this->request->get('status', 1); // 1-待完成 2-已完成
        $orderSn = $this->request->get('order_sn'); // 订单编号
        $page = $this->request->get('page', 1); //页数
        $limit = $this->request->get('limit', 10); //条数
        $where = [];
        if ($orderSn) {
            $where[] = ['mobile', 'like', '%'.$orderSn.'%'];
        }
        $siteId = Db::name('driver')->where(['id' => $this->user_info['id']])->value('site_id');
        $orderResult = Order::where(['order_status' => $status, 'del' => 0])
            ->where(['site_id' => $siteId])
            ->where($where)
            ->order('create_time desc')
            ->field('id, order_sn, order_status, order_amount, goods_id, create_time,consignee')
            ->paginate(['list_rows' => $limit, 'page' => $page]);

        $order = $orderResult->toArray();
        foreach ($order['data'] as &$items) {
            $goods = json_decode($items['goods_id'], true);
            foreach ($goods as $key => $v) {
                $goodsRes = Db::name('goods')->where(['id' => $v['goods_id']])->field('description')->find();
                $goods[$key]['description'] = $goodsRes['description'];
                $goods[$key]['image'] = $v['goods_image'];
            }
            $items['goods'] = $goods;
        }

        $this->_success('查询成功', $order);
    }
    //订单详情
    public function orderDetail()
    {
        $orderId = $this->request->get('order_id');
        $data['order_id'] = $orderId;
        $result = $this->validate($data,'app\driver\validate\Driver.detail');
        if($result !== true){
            $this->_error($result);
        }

        $order = Order::where(['id' => $orderId])->find();
        $row['address']['name'] = $order['consignee'];
        $row['address']['mobile'] = $order['mobile'];
        $row['address']['address'] = $order['address'].($order['address_detail'] ?: '');
        $latitude = User::where(['id' => $order['user_id']])->value('latitude');
        $row['address']['latitude'] = $latitude;

        $row['orderMsg']['order_sn'] = $order['order_sn'];  //订单编号
        $row['orderMsg']['order_status'] = $order['order_status'];  //订单状态
        $row['orderMsg']['is_recovery'] = $order['is_recovery'];  //是否需要旧瓶回收 0否1是
        $row['orderMsg']['create_time'] = $order['create_time'] ;  //下单时间
        $row['orderMsg']['user_remark'] = $order['user_remark'] ;  //订单备注
        $row['orderMsg']['pay_time'] = $order['pay_time'] ?: '';  //支付时间
        $row['orderMsg']['bottle_deposit'] = $order['bottle_deposit'];  //钢瓶押金
        $row['orderMsg']['settle_bottle_rent'] = $order['settle_bottle_rent'];  //租金
        $row['orderMsg']['floor_amount'] = $order['floor_amount'];  //楼层费
        $row['orderMsg']['bottle_amount'] = $order['bottle_amount'];  //气价
        $row['orderMsg']['order_amount'] = $order['order_amount'];  //实际付款金额
        $row['orderMsg']['complete_time'] = $order['complete_time'];  //订单完成时间
        $row['orderMsg']['displace_or_add'] = $order['displace_or_add'];  //订单完成时间
        $row['orderMsg']['bottle_send'] = isset($order['bottle_send']) ? json_decode($order['bottle_send'], true) : '';  //送瓶编号
        $row['orderMsg']['bottle_put'] =  isset($order['bottle_put']) ? json_decode($order['bottle_put'], true) : '';  //收瓶编号

        $site = Db::name('bottle_site')->where(['id' => $order['site_id']])->find();
        $row['siteMsg']['address'] = $site['address'];
        $row['siteMsg']['name'] = $site['name'];
        $row['siteMsg']['head_mobile'] = $site['head_mobile'];
        $row['siteMsg']['latitude'] = $site['latitude'];

        //配送员信息
        $driver = Db::name('driver')->where(['id' => $this->user_info['id']])->find();
        $row['driMsg']['name'] = $driver['dname'];
        $row['driMsg']['mobile'] = $driver['dmobile'];
        $row['driMsg']['avatar'] = $driver['davatar'];
        $row['driMsg']['site_name'] = Db::name('bottle_site')->where(['id' => $driver['site_id']])->value('name');
        $row['driMsg']['shi'] = Db::name('bottle')->where(['site_id' => $driver['site_id'], 'use_status' => 1, 'status' => 1])->count('status');
        $row['driMsg']['kong'] = Db::name('bottle')->where(['site_id' => $driver['site_id'], 'use_status' => 1, 'status' => 2])->count('status');


        $additionalPrice = 0;
        $goodsNum = 0;
        $rent = 0;
        $goods = OrderGoods::where(['order_id' => $orderId])->select();
        foreach ($goods as $key => $item) {
            $row['goods'][$key]['goods_name'] = $item['goods_name'];
            $row['goods'][$key]['goods_price'] = $item['goods_price'];
            $row['goods'][$key]['goods_num'] = $item['goods_num'];
            $rows = Db::name('goods')->where(['id' => $item['goods_id']])->find();
            $row['goods'][$key]['image'] = $rows['image'];
            $row['goods'][$key]['description'] = $rows['description'];
            $row['goods'][$key]['type'] = $rows['type'];

            //计算押金，租金
            if ($rows['type'] == 2) {
                //增购商品价
                $additionalPrice += $item['goods_price']*$item['goods_num'];
            } else {
                $goodsNum += $item['goods_num'];
            }
            $bottleNum = User::where(['id' => $order['user_id']])->value('bottle_num');
            $count = $bottleNum - $goodsNum;
            $newNum = 0; // 新押瓶
            if ($count < 0) {
                //需要付押瓶的钱
                $newNum = abs($count); //新的押瓶数

            }
            //租瓶押金结算记录表
            $bottlePayAmount = Db::name('bottle_rent_log')->where(['user_id' => $order['user_id'], 'if_pay' => 0])->sum('pay_amount');
            $month = date('m'); // 当前月份
            if ($month < 7) {
                $monthNum = 6 - $month;
            } else {
                $monthNum = 12 - $month;
            }
            //$rent = bcadd(bcmul(bcmul($monthNum,9), $newNum), $bottlePayAmount, 2);
            $rent = $order['settle_bottle_rent'];
        }
        $row['orderMsg']['additionalPrice'] = $additionalPrice;  //添加商品
        $row['orderMsg']['rent'] = $rent;  //钢瓶使用费
        $this->_success('查询成功', $row);
    }

    //确认送达
    public function smService()
    {
        Db::startTrans();
        try{
            $orderId = $this->request->post('order_id');
            $bottlePut = $this->request->post('bottle_put', []);
            $bottleSend = $this->request->post('bottle_send', []);
            $data['order_id'] = $orderId;
            $data['bottle_put'] = $bottlePut;
            $data['bottle_send'] = $bottleSend;
            $result = $this->validate($data,'app\driver\validate\Driver.sm');
            if($result !== true){
                throw new Exception($result);
            }
            //判断钢瓶是否真实
            if (empty(count($bottleSend))) {
                throw new Exception('请填写钢瓶编码');
            }
            $uid = $this->user_info['id'];
            $driver = Db::name('driver')->where(['id' => $uid])->find();
            foreach($bottleSend as $item) {
                $results = Db::name('bottle')->where(['code' => $item, 'status' => 1, 'use_status' => 1])->find();
                if (!$results) {
                    throw new Exception('钢瓶:'.$item.',必须要为实瓶，且为配送站点的钢瓶');
                }
                if ($results['site_id'] != $driver['site_id']) {
                    throw new Exception('钢瓶编码{'.$item.'}配送员所属站点与钢瓶编码所属站点不一致');
                }
            }

            $order = Order::where(['id' => $orderId, 'order_status' => 1])->find();
            $user = User::where(['id' => $order->user_id])->find();
            if (!$order) {
                throw new Exception('不存在该订单');
            }
            $time = date('Y-m-d H:i:s');
            if ($order->displace_or_add == 2) {
                //新增押瓶
                if ($data['bottle_put']) {
                    $bottlePut = [];
                }

                if (($order->bottle_num != count($bottleSend))) {
                    throw new Exception('送瓶编号数量与订气数量不同');
                }
                //配送完成增加用户的押瓶数
                Db::name('user')->where(['id' => $order['user_id']])->inc('bottle_num', $order->bottle_num)->update();


            } else {
                //押瓶置换
                if (($order->bottle_num != count($bottleSend)) || ($order->bottle_num != count($bottlePut))) {
                    throw new Exception('送瓶编号数量跟取瓶编号数量都必须与订气数量相同');
                }
            }


            //生成钢瓶租金记录是上一个置换回来的瓶。置换瓶根据时间计算使用多少天

            if ($bottlePut) {
                //置换逻辑-取瓶4
                //配送完成更新完成时间
//                Db::name('bottle_rent_log')
//                    ->where(['user_id' => $order['user_id'],'if_pay'=>0])
//                    ->whereLike('bottle_code', '%'.implode('',$bottlePut).'%')
//                    ->update([
//                    'end_time'=> date('Y-m-d',time())
//                ]);
//                echo  Db::name('bottle_rent_log')->getLastSql();die;
                $orderSend = Db::name('bottle')->whereIn('code', $bottlePut)->field('updatetime as pay_time, user_id')->find();

                if ($orderSend) {
                    $type ='距离下单时间到置换回来钢瓶租金计算';
                    $date1 = date_create(date("Y-m-d", strtotime($orderSend['pay_time'])));
                    $date2 = date_create(date("Y-m-d"));
                    $interval = date_diff($date1, $date2);
                    $day = $interval->days;  //相差天数
                    if (empty($day)) {
                        $day = 1;
                    }
                    $bottleRent = Db::name('user')->where(['id' => $order['user_id']])->value('bottle_rent');
                    $priceDay = $bottleRent ?: (new FeiHong)->getConfig('pay', 'bottle_rent'); //每天租金金额
                    // 钢瓶押金租金只要取订单表 jiangsheng
//                    $priceDay  = $order['bottle_deposit'];
//                    foreach ($bottlePut as $code) {
//                        $sum = bcmul($day, $priceDay, 2);
//                        Db::name('bottle_rent_log')->insert([
//                            'user_id' => $orderSend['user_id'],
//                            'type' => $type,
//                            'bottle_code' => $code,
//                            'pay_amount' => $sum,
//                            'if_pay' => 0,
//                            'pay_time' => 0,
//                            'create_time' => $time,
//                        ]);
//
//                    }
                    $sum = bcmul(count($bottlePut),bcmul($day, $priceDay, 2), 2);
                    $co = [];
                    $j = 0;
                    foreach ($bottlePut as $code) {
                        $co[$j]['bottle_code'] = $code;
                        $co[$j]['time'] = date('Y-m-d', strtotime($orderSend['pay_time']));
                        $j++;
                    }

                    Db::name('bottle_rent_log')->insert([
                        'user_id' => $orderSend['user_id'],
                        'type' => $type,
                        'bottle_code' => json_encode($co, 256),
                        'pay_amount' => $sum,
                        'if_pay' => 0,
                        //'pay_time' => 0,
                        'create_time' => $time,
                        'end_time'=> date('Y-m-d',time())
                    ]);

                }
            }

            $order->order_status = 2;
            $order->admin_id = $uid;
            $order->bottle_put = json_encode($bottlePut, 256);
            $order->bottle_send = json_encode($bottleSend, 256);
            $order->complete_time = $time;
            $order->save();
            //钢瓶操作记录表

            $daraArrPut = [];
            $daraArrSend = [];
            $name = Db::name('bottle_site')->where(['id' => $driver['site_id']])->value('name');
            $uiq4 = '4'.uniqid().$this->user_info['id']; // 用来关联标识
            $priceCount = 0;
            foreach ($bottlePut as $key => $item) {
                //钢瓶取瓶
                $res = Db::name('bottle')->where(['code' => $item])->find();
                if (!empty($res['site_id'])) {
                    throw new Exception('该钢瓶{'.$item.'}已经存在绑定站点');
                }
                if ($res['user_id'] != $order['user_id']){
                    throw new Exception('该钢瓶{'.$item.'}已经绑定其他用户');
                }
                $priceCount += $res['bottle_deposit'];
                $daraArrPut[$key]['bottle_code'] = $item;
                $daraArrPut[$key]['admin_id'] = $uid;
                $daraArrPut[$key]['uid'] = $uiq4;
                $daraArrPut[$key]['type'] = 4;
                $daraArrPut[$key]['order_id'] = $orderId;
                $daraArrPut[$key]['info'] = ' 详细信息：完成订单'.$order->order_sn.'从客户'.$user->mobile.'取瓶至'.$name;
                $daraArrPut[$key]['create_time'] = $time;

                Db::name('bottle')
                    ->where(['code' => $item])
                    ->update([
                            'user_id' => '',
                            'site_id' => $driver['site_id'],
                            'status' => 2,
                            'bottle_deposit' => 0 ,
                            'updatetime' => $time
                        ]);
            }
            $uiq5 = '5'.uniqid().$this->user_info['id']; // 用来关联标识
            if ($order->displace_or_add == 2) {
                $bottleDeposit = $order->bottle_deposit / $order->bottle_num;
            } else {
                //置换金额
                $bottleDeposit = $priceCount / count($bottlePut);
            }

            foreach ($bottleSend as $key => $items) {
                //配送成功钢瓶会绑定用户，去除站点。
                $res = Db::name('bottle')->where(['code' => $items])->find();

                if (!empty($res['user_id'])) {
                    throw new Exception('该钢瓶{'.$items.'}已经存在绑定用户');
                }
                //钢瓶送瓶
                $daraArrSend[$key]['bottle_code'] = $items;
                $daraArrSend[$key]['admin_id'] = $uid;
                $daraArrSend[$key]['uid'] = $uiq5;
                $daraArrSend[$key]['type'] = 5;
                $daraArrSend[$key]['order_id'] = $orderId;
                $daraArrSend[$key]['info'] = ' 详细信息：完成订单'.$order->order_sn.'从'.$name.'送瓶至客户'.$user->mobile;
                $daraArrSend[$key]['create_time'] = $time;
                  //钢瓶押金必须要取订单表的下单收取押金
                Db::name('bottle')->where(['code' => $items])->update(['user_id' => $order->user_id, 'site_id' => '',
                    'bottle_deposit' => $bottleDeposit, 'updatetime' => $time ]);
            }

            $all = array_merge($daraArrPut, $daraArrSend);
            $result = Db::name('bottle_log')->insertAll($all);
            //配送完成，不管是新增和置换都是以配送员的站点为准。
            $site_id = $driver['site_id'];
            if ($result) {
                // 生成进1操作记录,2出库记录，
                if ($bottlePut) {
                    // 置换 4-订单取瓶
                    $bIdPut = Db::name('bottle_log')
                        ->whereIn('bottle_code', $bottlePut)
                        ->where(['type'=>4,'admin_id' => $this->user_info['id'],'create_time'=>$time])
                        ->column('id');
                    $bIdJsonPut = json_encode($bIdPut, 256);
                    $resPut = Db::name('bottle_exet_log')
                        ->insert(['bootle_site_id'=>$site_id,'bottle_log_id' => $bIdJsonPut,  'create_time' => $time, 'uid' => $uiq4]);
                    if(!$resPut) {
                        throw new Exception('录入失败');
                    }
                }
                if ($bottleSend) {
                    //新增 5-订单送瓶
                    $bId = Db::name('bottle_log')
                        ->whereIn('bottle_code', $bottleSend)
                        ->where(['type'=>5,'admin_id' => $this->user_info['id'],'create_time'=>$time])
                        ->column('id');
                    $bIdJson = json_encode($bId, 256);
                    //站点钢瓶进出库记录表
                    $res = Db::name('bottle_exet_log')
                        ->insert(['bootle_site_id'=>$site_id,'bottle_log_id' => $bIdJson,  'create_time' => $time, 'uid' => $uiq5]);
                    if(!$res) {
                        throw new Exception('录入失败');
                    }
                }

            }
            Db::name('user')->where(['id' => $order['user_id']])->update(['order_last_time' => $time]);
            Db::commit();
            $this->_success('确认送达成功');
        }catch (Exception $e) {
            Db::rollback();
            $this->_error($e->getMessage());
        }

    }

    public function userInfo()
    {
        $token = $this->user_info['token'];
        $user = Db::name('driver u')
            ->join('session s', 'u.id=s.user_id')
            ->where(['s.token' => $token])
            ->field('u.*,s.token,s.client')
            ->find();
        if ($user) {
            $user['siteName'] = Db::name('bottle_site')->where(['id' => $user['site_id']])->value('name');
        }
         $this->_success('查询成功', $user);
    }

    //退出登录
    public function logout()
    {
        try {
            $userId = $this->user_info['id'];
            $token = $this->user_info['token'];
            $session = Db::name('session')->where(['user_id' => $userId, 'type' => 1])->update(['token' => '']);
            if (!$session) {
                throw new Exception('退出失败');
            }
            //登录缓存删除
            $token_cache = new TokenCache($token, ['token' => $token, 'type' => 1], 1);
            $token_cache->del();
            $this->_success('退出成功');
        }catch (Exception $e) {
            $this->_error($e->getMessage());
        }
    }

    //站点
    public function site()
    {
        $site = Db::name('bottle_site')->where(['del' => 0])->select();
        foreach ($site as &$item) {
            $item['shi'] = Db::name('bottle')->where(['site_id' => $item['id'], 'use_status' => 1, 'status' => 1])->count('status');
            $item['kong'] = Db::name('bottle')->where(['site_id' => $item['id'], 'use_status' => 1, 'status' => 2])->count('status');
        }
        $this->_success('查询成功', $site);
    }

    //站点详情
    public function siteDetail()
    {
        $id = $this->request->get('id');
        $data['id'] = $id;
        $result = $this->validate($data,'app\driver\validate\Driver.site');
        if($result !== true){
            $this->_error($result);
        }
        $site = Db::name('bottle_site')->where(['id' => $id,'del' => 0])->find();
        $bottle = DB::name('bottle')->where(['site_id' => $site['id'], 'use_status' => 1])->select();
        //计算站点实瓶，空瓶
        $shi = ['num' => 0, 'data' => []];
        $kong = ['num' => 0, 'data' => []];
        $i = 0;
        $j = 0;
        foreach ($bottle as $item) {
            if ($item['status'] == 1) {
                $shi['num'] += 1;
                $shi['data'][$i]['code'] = $item['code'];
                $i++;
            } else {
                $kong['num'] += 1;
                $kong['data'][$j]['code'] = $item['code'];
                $j++;
            }
        }

        $site['shi'] = $shi;
        $site['kong'] = $kong;


        $this->_success('查询成功', $site);
    }

    //录入钢瓶流转
    public function saveBottle()
    {
        try{
            Db::startTrans();
            $post = $this->request->post();
            $data['type'] = $post['type']; //2-充装 3-转运出 7-转运回
            $data['site'] = $post['site']; //流入站点
            $data['mySite'] = $post['my_site']; //所属站点

            if (count($post['bottle_code']) < 1) {
                throw new Exception('钢瓶编码必填');
            }
            $result = $this->validate($data,'app\driver\validate\Driver.save');
            if($result !== true){
                $this->_error($result);
            }
            $row = [];
            //（类型：转运 操作人：崔智杰 时间：2023-07-17 16:08 详细信息：西塘供应站转运至飞虹燃气）
            $name = Db::name('bottle_site')->where(['id' => $data['mySite']])->value('name');
            $dname = Db::name('bottle_site')->where(['id' => $data['site']])->value('name');
            $uiq = $data['type'].uniqid().$this->user_info['id']; // 用来关联标识
            $siteArr = [];
            $time = date('Y-m-d H:i:s');
            $bottleCode = array_unique($post['bottle_code']);
            $bottle_log_id  = []; //数组
            foreach ($bottleCode as $key => $item) {
                    $row['bottle_code'] = $item;
                    $row['type'] = $data['type'];
                    $row['uid'] = $uiq;
                    $row['admin_id'] = $this->user_info['id'];
//                    $row[$key]['info'] = '类型：'.\app\driver\model\Driver::getTypeText($data['type']).' 操作人：'.$this->user_info['dname'].' 时间：'.
//                        $time.' 详细信息：'.$name.\app\driver\model\Driver::getTypeText($data['type']).'至'.$dname;
                    $row['info'] = ' 详细信息：'.$name.\app\driver\model\Driver::getTypeText($data['type']).'至'.$dname;
                    $row['create_time'] = $time;
                    $row['site_id'] = $data['site'];
                    $row['my_site_id'] = $data['mySite'];
                    $siteArr[] = $item;
                $bottle_log_id[] = Db::name('bottle_log')->insertGetId($row);
            }

            if ( $data['type'] == 7) {
                Db::name('bottle')->whereIn('code', $siteArr)->update(['site_id' => $data['site'], 'updatetime' => $time]); //站点转站点
            }
            
            if (count($bottle_log_id)>0) {
//                $bId = Db::name('bottle_log')->whereIn('bottle_code', $bottleCode)
//                    ->where(['admin_id' => $this->user_info['id']])->column('id');
                $bIdJson = json_encode($bottle_log_id, 256);
                $res = Db::name('bottle_exet_log')
                    ->insert(['bottle_log_id' => $bIdJson, 'bootle_site_id' => $post['my_site'], 'create_time' => $time, 'uid' => $uiq]);
                if(!$res) {
                    throw new Exception('录入失败');
                }
                if ( $data['type'] == 7) {
                    //钢瓶调拨，被流入的站点也生成数据
                    $res2 = Db::name('bottle_exet_log')
                        ->insert(['bottle_log_id' => $bIdJson, 'bootle_site_id' => $post['site'], 'create_time' => $time, 'uid' => $uiq]);
                    if(!$res2) {
                        throw new Exception('录入失败2');
                    }
                }
            }

            if ($data['type'] == 2) {
                //充装变实瓶
                Db::name('bottle')->whereIn('code', $post['bottle_code'])->update(['status' => 1]);
            }
            Db::commit();
            $this->_success('录入成功');
        }catch (Exception $e) {
            Db::rollback();
            $this->_error($e->getMessage());
        }

    }

    //进出库记录
    public function logDetail()
    {
//        $page = $this->request->get('page', 1); //页数
//        $siteId = $this->request->get('site_id', 1); //站点ID筛选
//        $limit = $this->request->get('limit', 10); //条数
//        $userId = $this->user_info['id'];
//        $where = " 1=1 ";
//        if ($siteId) {
//            $where = "my_site_id = {$siteId}";
//        }
//
//        $result = Db::name('bottle_log')->where($where)->where(['admin_id' => $userId])->order('create_time desc')
//            ->paginate(['list_rows' => $limit, 'page' => $page]);
//        $row = $result->toArray();
//        $dname = Db::name('driver')->where(['id' => $userId])->value('dname');
//        $uidArr = [];
//        $code = [];
//        foreach ($row['data'] as $item) {
//           $code[$item['uid']][] = $item['bottle_code'];
//        }
//
//        foreach ($row['data'] as $key => $item) {
//            if (!in_array($item['uid'], $uidArr)) {
//                $uidArr[] = $item['uid'];
//                $row['data'][$key]['dname'] = $dname;
//                $row['data'][$key]['bottle_code'] = $code[$item['uid']] ? implode(',', $code[$item['uid']] ) : '' ;
//                $row['data'][$key]['type_name'] = \app\driver\model\Driver::getTypeText($item['type']);
//            } else {
//                unset($row['data'][$key]);
//            }
//
//        }

//        $row['data'] = array_values($row['data']);
//        $this->_success('查询成功', $row);

        $page = $this->request->get('page', 1); //页数
        $siteId = $this->request->get('site_id', 1); //站点ID筛选
        $limit = $this->request->get('limit', 10); //条数
        $userId = $this->user_info['id'];
        $where['bootle_site_id'] = $siteId;
        $bottleExetLog = Db::name('bottle_exet_log')->where($where)->order('create_time desc')->paginate(['list_rows' => $limit, 'page' => $page])->each(function($v,$k){
            $bottleLog = Db::name('bottle_log')->whereIn('id',json_decode($v['bottle_log_id'],true))->select();
            // 解析bottle_code
            $v['bottle_code'] =  implode(',',array_column($bottleLog, 'bottle_code'));
            $v['admin_id'] = $bottleLog[0]['admin_id']??'';
            $v['dname'] =  Db::name('driver')->where(['id' => $bottleLog[0]['admin_id']])->value('dname')??'';
            $v['create_time'] = $bottleLog[0]['create_time']??'';
            $v['info'] = $bottleLog[0]['info']??'';
            $v['site_id'] = $v['bootle_site_id']??'';
            $v['type'] = $bottleLog[0]['type']??'';
            $v['type_name'] = \app\driver\model\Driver::getTypeText($bottleLog[0]['type'])??'';
            return $v;
        });
        $this->_success('查询成功', $bottleExetLog);
//        var_dump($bottleExetLog);
        /*
        admin_id: 20
        bottle_code: "000050,000051,000052,000053"
        create_time: "2023-09-22 00:08:02"
        dname: "星沙司机"
        id: 411
        info: " 详细信息：飞虹燃气钢瓶调拨至星沙站点"
        my_site_id: 3
        order_id: 0
        site_id: 7
        type: 7
        type_name: "钢瓶调拨"
        uid: "7650c6a628e76620"
        */

    }

    //配置接口
    public function showConfig()
    {
        $type = $this->request->get('type');
        $name = $this->request->get('name');
        $this->_success('查询成功', (new FeiHong())->getConfig($type, $name));
    }

    //司机接单提示信息定时器跑
    public function orderMsg()
    {
        $siteId = $this->user_info['site_id']; //站点ID
        if ($siteId) {
            //用户下单保存下单信息到ls_message表
            //存在站点ID推送订单信息
            $message = Db::name('message')->where(['status' => 0])->select();


        }
    }

    //钢瓶流转信息
    public function turnInfo()
    {
        $liang = 1; // 订气的数量
        $sum = bcmul($liang,bcmul(1, 0.01, 2), 2);
        dd($sum);
    }
    public function bottleInput(){
        $post = $this->request->post();
        $result = $this->validate($post,'app\admin\validate\Bottle');
        $post['admin_id'] = $this->user_info['id']??'16';
        if($result !== true){
            $this->_error($result);
        }
        if($result === true){
            try{
//                $result = BottleLogic::add($post);

//        $bottleLog = new BottleLogLogic();
                Db::startTrans();
                //拼接数据
                $data = [
                    'site_id'     => $post['site_id'],
                    'code'        => $post['code'],
                    'shared_code' => $post['shared_code'],
                    'remark'      => $post['remark'],
                    'status'      => 2,//钢瓶默认状态为空瓶
                    'use_status'  => 1,//默认启用
                    'createtime'  => date("Y-m-d H:i:s",time()),
                ];
                $logData = [
                    'bottle_code' => $data['code'],
                    'type'=>1,
                    'admin_id'=>$post['admin_id'],
                    'info'=>'新瓶入库到飞虹燃气',
                ];

                $logData['create_time'] =date("Y-m-d H:i:s",time());
                $sta1 = Db::name('bottle_log')->insertGetId($logData);

                $stat2 = Db::name('bottle')->insert($data);
                $bottle_exet_log = [
                    'bottle_log_id'=>json_encode([$sta1]),
                    'bootle_site_id'=>$post['site_id'],
                    'create_time'=>date("Y-m-d H:i:s",time())
                ];
                $sta3 = Db::name('bottle_exet_log')->insert($bottle_exet_log);
                if($sta1==true && $stat2==true && $sta3==true){
                    Db::commit();
                    $this->_success('新增成功',$result);
                }
                Db::rollback();

            } catch (Exception $e){
                Db::rollback();
                $this->_error($e->getMessage());
            }
            $result = '新增失败';
        }
        $this->_error($result);
    }
    public function siteList(){
        $where[] = ['del', '=', 0];
        $where[] = ['type', '=', 1];
        $bottle_site_list = Db::name('bottle_site')
            ->where($where)
            ->select();
        $this->_success('查询成功',$bottle_site_list);
    }
}